package com.sanley.piss.web.manager.shiro.config;

import com.gitee.dreamkaylee.shiro.ShiroPlusProperties;
import com.gitee.dreamkaylee.shiro.authc.credential.CredentialsRetryLimitCredentialsMatcher;
import com.gitee.dreamkaylee.shiro.authz.repository.ShiroPrincipalRepository;
import com.gitee.dreamkaylee.shiro.realm.AuthorizingRealmListener;
import com.sanley.piss.web.manager.shiro.realm.UsernamePasswordRealm;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.realm.Realm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author limk
 * @date 2020/12/18 15:43
 */
@Configuration
public class ShiroConfig {

    @Bean
    public CacheManager cacheManager() {
        return new MemoryConstrainedCacheManager();
    }

    @Bean
    public CredentialsRetryLimitCredentialsMatcher credentialsMatcher() {
        CredentialsRetryLimitCredentialsMatcher matcher = new CredentialsRetryLimitCredentialsMatcher();
        matcher.setCacheManager(cacheManager());
        matcher.setHashIterations(5);
        matcher.setHashAlgorithmName("MD5");
        return matcher;
    }

    @Bean
    public Realm defRealm(ShiroPrincipalRepository repository, ShiroPlusProperties properties, @Autowired(required = false) List<AuthorizingRealmListener> realmsListeners) {
        UsernamePasswordRealm usernamePasswordRealm = new UsernamePasswordRealm();
        usernamePasswordRealm.setRepository(repository);
        usernamePasswordRealm.setCredentialsMatcher(credentialsMatcher());
        usernamePasswordRealm.setRealmsListeners(realmsListeners);
        usernamePasswordRealm.setCachingEnabled(properties.isCachingEnabled());
        usernamePasswordRealm.setAuthenticationCachingEnabled(properties.isAuthenticationCachingEnabled());//
        usernamePasswordRealm.setAuthenticationCacheName(properties.getAuthenticationCacheName());//
        usernamePasswordRealm.setAuthorizationCachingEnabled(properties.isAuthorizationCachingEnabled());
        usernamePasswordRealm.setAuthorizationCacheName(properties.getAuthorizationCacheName());
        return usernamePasswordRealm;
    }



}
